#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
时间工具函数
@api-version: 1.0.0
"""

from datetime import datetime
import pytz

# 中国时区
CHINA_TZ = pytz.timezone('Asia/Shanghai')

def get_local_now():
    """获取当前本地时间（中国时区）"""
    return datetime.now(CHINA_TZ).replace(tzinfo=None)

def get_utc_now():
    """获取当前UTC时间"""
    return datetime.utcnow()

def utc_to_local(utc_dt):
    """将UTC时间转换为本地时间"""
    if utc_dt is None:
        return None
    
    # 如果已经有时区信息，先转换为UTC
    if utc_dt.tzinfo is not None:
        utc_dt = utc_dt.astimezone(pytz.UTC).replace(tzinfo=None)
    
    # 将UTC时间标记为UTC时区
    utc_dt = pytz.UTC.localize(utc_dt)
    
    # 转换为本地时区
    local_dt = utc_dt.astimezone(CHINA_TZ)
    
    # 返回不带时区信息的本地时间
    return local_dt.replace(tzinfo=None)

def local_to_utc(local_dt):
    """将本地时间转换为UTC时间"""
    if local_dt is None:
        return None
    
    # 如果已经有时区信息，先转换为本地时区
    if local_dt.tzinfo is not None:
        local_dt = local_dt.astimezone(CHINA_TZ).replace(tzinfo=None)
    
    # 将本地时间标记为中国时区
    local_dt = CHINA_TZ.localize(local_dt)
    
    # 转换为UTC时区
    utc_dt = local_dt.astimezone(pytz.UTC)
    
    # 返回不带时区信息的UTC时间
    return utc_dt.replace(tzinfo=None)

def format_datetime(dt, format_str='%Y-%m-%d %H:%M:%S'):
    """格式化时间"""
    if dt is None:
        return None
    return dt.strftime(format_str)